import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { createUserAuth, createUserSignLibaoAuth, reduceSendAuth, selectUserAuth, selectUseSignLibaorAuth, userAuthUpdate } from './user_auth.service';
import { isToday } from '../custom/custom';
import { updateHouse } from '../user/user.service';

/**
 * 注册创建用户表
 */
export const storeAuthUser = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取用户ID
  const user_id = request.user.id;

  const { vip_days, type } = request.body;

  // 按用户 ID 查询内容
  let isUserAuthId = await selectUserAuth(user_id);
  
  let startTime = parseInt(`${new Date().getTime() / 1}`, 10)
  let endTime = 0;
  let post = {};

  if (isUserAuthId[0].endTime > startTime) {
    endTime = parseInt(`${isUserAuthId[0].endTime}`, 10) + 86400000 * vip_days
    post = { user_id: user_id, vip_days: vip_days, startTime: startTime, endTime: endTime, type: type }
  } else {
    endTime = parseInt(`${startTime + 86400000 * vip_days}`, 10)
    post = { user_id: user_id, vip_days: vip_days, startTime: startTime, endTime: endTime, type: type }
  }

  try {
    if (Object.keys(isUserAuthId).length !== 0 && isUserAuthId[0].user_id && isUserAuthId[0].user_id > 0) {
      const data = await userAuthUpdate(parseInt(`${user_id}`, 10), post);
      
      // 返回数据
      response.send(data)
    } else {
      await createUserAuth(post);

      // 返回数据
      response.send({
        msg: 'create success !',
        status: 201
      })
    }
  } catch (error) {
    next(error);
  }
}

/**
 * 购买会员后增加权限
 */
export const requestUserAuth = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取权限
  const { user_id, vip_days, type, note } = request.body;

  // 写入备注
  if (note) {
    let post = { note: note }
    await updateHouse(post, user_id)
  }

  // 按用户 ID 查询内容
  let isUserAuthId = await selectUserAuth(user_id);;

  let startTime = parseInt(`${new Date().getTime() / 1}`, 10);
  let endTime = parseInt(`${startTime + 86400000 * vip_days}`, 10)
  const post = { user_id: user_id, vip_days: vip_days, startTime: startTime, endTime: endTime, type: type }

  try {
    if (Object.keys(isUserAuthId).length !== 0 && isUserAuthId[0].user_id && isUserAuthId[0].user_id > 0) {
      const data = await userAuthUpdate(parseInt(`${user_id}`, 10), post);

      // 返回数据
      response.send(data)
    } else {
      await createUserAuth(post);

      // 返回数据
      response.send({
        msg: 'create success !',
        status: 201
      })
    }
  } catch (error) {
    next(error);
  }
};

/**
 * 添加一天会员（签到）
 */
export const oneVipUserAuth = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取权限
  const { user_id, vip_days } = request.body;

  // 按用户 ID 查询内容
  let isUserAuthId = await selectUserAuth(user_id);

  let startTime = parseInt(`${new Date().getTime() / 1}`, 10);
  let endTime = 0;
  if(isUserAuthId[0].endTime > startTime) {
    endTime = parseInt(`${isUserAuthId[0].endTime}`, 10) + parseInt(`${86400000 * vip_days}`, 10)
    let post_libao = { user_id: user_id, startTime: startTime }
    
    let isLibao = await selectUseSignLibaorAuth(user_id) // 检查这周是否有签到礼包
    let isTodayTime = await isToday(isLibao[0]?.startTime) // 检查礼包是否领过
    
    if (!isTodayTime) {
      await createUserSignLibaoAuth(post_libao) // 添加签到礼包
    } else {
      // 返回数据
      return response.send({
        msg: '签到礼包已存在',
        status: 201
      })
    }


  } else {
    endTime = parseInt(`${startTime + (86400000 * vip_days)}`, 10)
  }
  
  const post = { user_id: user_id, vip_days: vip_days, startTime: startTime, endTime: endTime }
  
  try {
    if (Object.keys(isUserAuthId).length !== 0 && isUserAuthId[0].user_id && isUserAuthId[0].user_id > 0) {
      const data = await userAuthUpdate(parseInt(`${user_id}`, 10), post);

      // 返回数据
      response.send(data)
    } else {
      await createUserAuth(post);

      // 返回数据
      response.send({
        msg: 'create success !',
        status: 201
      })
    }
  } catch (error) {
    next(error);
  }
};

/**
 * 获取用户权限
 */
export const userAuth = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取用户 ID
  const { user_id } = request.body;

  try {
    const data = await selectUserAuth(user_id);
    let vipTime = '0';

    if (data[0]) {
      let endTime = data[0].endTime;
      let newTime = Math.floor(new Date().getTime() / 1);
      if (newTime > endTime) {
        vipTime = '0';
      } else {
        vipTime = `${ Math.ceil((endTime - newTime) / 86400000) }`;
      }
    }
    
    let res = { name: '会员剩余时间', vipTime: vipTime };

    response.send(res);
  } catch (error) {
    next(error);
  }
};


